package com.adwin.addcoin.ui.login

import android.app.Activity
import android.app.Application
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultRegistryOwner
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.BuildConfig
import com.adwin.addcoin.R
import com.adwin.addcoin.repository.Repost.BurialSiteRepostUtils
import com.adwin.addcoin.repository.net.RetrofitClient
import com.adwin.addcoin.repository.SchedulerTransformer
import com.adwin.addcoin.repository.api.TestApi
import com.adwin.addcoin.ui.main.MainActivity
import com.adwin.addcoin.utils.dataStore
import com.adwin.addcoin.utils.getRePost
import com.adwin.addcoin.utils.getUserGaid
import com.adwin.addcoin.utils.installRepost
import com.adwin.addcoin.utils.log
import com.adwin.addcoin.utils.saveRepostNumber
import com.adwin.addcoin.utils.saveToken
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.login.LoginManager
import com.google.android.gms.auth.api.identity.GetSignInIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.lang.Exception
import java.security.MessageDigest
import java.util.Locale

class LoginViewModel(application: Application) : AndroidViewModel(application) {

    val tvPolicy by lazy { MutableLiveData<String>() }

    init {
//        "By logging in, you agree to Addcoin’s Privacy Poli"
//        tvPolicy.value = addTextClick()
    }

    private val mApplication: Application = application

    //google web应用id，Android应用id失败
    private val googleRequestIdToken = mApplication.getString(R.string.google_request_id_token)

    //        private val googleRequestIdToken =
//        "154500623814-rdr94ff6f1h31flfffr224277u2je59g.apps.googleusercontent.com"

    fun googleLogin(
        onSuccess: (pendingIntent: PendingIntent) -> Unit
    ) {
//Google Sign-In提供了检查现在是否已有登录账号的API
//            val lastSignedInAccount = GoogleSignIn.getLastSignedInAccount(activity)
//            if (null != lastSignedInAccount)

        val signInRequestLocal = GetSignInIntentRequest.Builder()
            .setServerClientId(googleRequestIdToken)
            .build()
        Identity.getSignInClient(mApplication)
            .getSignInIntent(signInRequestLocal)
            .addOnSuccessListener { pendingIntent ->
                onSuccess(pendingIntent)
            }.addOnFailureListener { e ->
                AddCoinApplication.myLog(e.localizedMessage)
            }
    }

    fun guestLogin(activity: Activity){
        MainScope().launch {
            RetrofitClient.getInstance().getService(TestApi::class.java)
                .guestLogin().compose(SchedulerTransformer()).subscribe({
                    if (it.isSuccessful){
                        if (it.body()?.code == 200){
                            if (it.isSuccessful) {
                                if (it.body()?.code == 200){
                                    Toast.makeText(activity, "success:${it.body()?.data}", Toast.LENGTH_LONG).show()
                                    val token = it.body()?.data?.auth_token?:""
                                    viewModelScope.launch(Dispatchers.IO) {
                                        activity.installRepost("guest_Login_ok")
                                        activity.dataStore.saveToken(token)
                                    }
                                    AddCoinApplication.instance.isGuestLogin = true
                                    AddCoinApplication.myLog("success:${it.body()?.data}")
                                    AddCoinApplication.token = it.body()?.data?.auth_token?:""
                                    activity.startActivity(Intent(activity,MainActivity::class.java))
                                    activity.finish()
                                }else{
                                    Toast.makeText(activity, "fail:${it.body()?.msg}", Toast.LENGTH_LONG).show()
                                }
                            } else {
                                viewModelScope.launch(Dispatchers.IO) {
                                    activity.installRepost("guest_Login_error")
                                }
                                Toast.makeText(activity, "fail:${it.errorBody()?.string()}", Toast.LENGTH_LONG).show()
                            }
                        }
                    }
                },{
                    viewModelScope.launch(Dispatchers.IO) {
                        activity.installRepost("guest_Login_error")
                    }
                    Toast.makeText(activity, "error:${it.localizedMessage}", Toast.LENGTH_LONG).show()
                })
        }
    }

    /**
     * @param source 来源 google facebook
     * @param oauth2Token 三方授权令牌
     */
    fun login(activity: Activity, source: String, oauth2Token: String) {
        MainScope().launch {
            var gaid = AddCoinApplication.gaid
            if (TextUtils.isEmpty(gaid)){
                gaid = activity.getUserGaid()
            }
            val country = Locale.getDefault().country
            val jo = JsonObject()
            jo.addProperty("source", source)
            jo.addProperty("oauth2Token", oauth2Token)
            jo.addProperty("id", gaid)
            jo.addProperty("country", country)
            val body = FormBody.create(MediaType.parse("application/json;charset=utf-8"), jo.toString())
            val subscribe = RetrofitClient.getInstance().getService(TestApi::class.java)
                .login(body)
                .compose(SchedulerTransformer())
                .subscribe({
                    //success
                    if (it.isSuccessful) {
                        if (it.body()?.code == 200){
                            Toast.makeText(activity, "success", Toast.LENGTH_LONG).show()
                            val token = it.body()?.data?.auth_token?:""
                            viewModelScope.launch(Dispatchers.IO) {
                                activity.installRepost("$source _Login_ok")
                                activity.dataStore.saveToken(token)
                            }
                            AddCoinApplication.instance.isGuestLogin = false
                            AddCoinApplication.myLog("success:${it.body()?.data}")
                            AddCoinApplication.token = it.body()?.data?.auth_token?:""
                            activity.startActivity(Intent(activity,MainActivity::class.java))
                            activity.finish()
                        }else{
                            Toast.makeText(activity, "fail:${it.body()?.msg}", Toast.LENGTH_LONG).show()
                        }
                    } else {
                        viewModelScope.launch(Dispatchers.IO) {
                            activity.installRepost("$source _Login_error")
                        }
                        Toast.makeText(activity, "fail:${it.errorBody()?.string()}", Toast.LENGTH_LONG).show()
                    }

                }, {
                    viewModelScope.launch(Dispatchers.IO) {
                        activity.installRepost("$source _Login_error")
                    }
                    Toast.makeText(activity, "error:${it.localizedMessage}", Toast.LENGTH_LONG).show()
                })
        }

    }


    fun googleLogout(activity: FragmentActivity?) {
        activity?.let {
            Identity.getSignInClient(activity)
                .signOut()
                .addOnSuccessListener {
                    AddCoinApplication.myLog("Google账号退出登录成功")
                }
        }
    }

    fun facebookLogin(
        activityResultRegistryOwner: ActivityResultRegistryOwner,
        metaCallbackManager: CallbackManager
    ) {
//        checkKeyStoreHash()
        //Facebook登录提供了检查现在是否已有登录账号的API

        val currentAccessTokenActive = AccessToken.isCurrentAccessTokenActive()
        AddCoinApplication.myLog("Meta login current AccessToken active :$currentAccessTokenActive")
//        if (!currentAccessTokenActive) {
//            LoginManager.getInstance().logIn(
//                activityResultRegistryOwner,
//                metaCallbackManager,
//                listOf("public_profile")
//            )
//        }


//        LoginManager.getInstance().logInWithReadPermissions(
//            activity
//            , listOf("public_profile")
//        )


    }

    fun facebookLogout() {
        LoginManager.getInstance().logOut()
    }


    /**
     * facebook散射key
     */
     fun checkKeyStoreHash() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val info = mApplication.packageManager.getPackageInfo(
                    BuildConfig.APPLICATION_ID,
                    PackageManager.GET_SIGNING_CERTIFICATES
                )

                val signingInfo = info.signingInfo
                val apkContentsSigners = signingInfo.apkContentsSigners

                for (signature in apkContentsSigners) {
                    val md: MessageDigest = MessageDigest.getInstance("SHA")
                    md.update(signature.toByteArray())
                    val keyStoreHash = Base64.encodeToString(md.digest(), Base64.DEFAULT)
                    "秘钥散列：$keyStoreHash".log()
//                    AddCoinApplication.myLog("秘钥散列：$keyStoreHash")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}